import axios from 'axios'
import { getToken } from '@/utils/auth'

const baseUrl = import.meta.env.VITE_APP_BASE_API

export function downLoadByUrl(url, options = {}, textName) {
  return new Promise((resolve, reject) => {
    axios.defaults.headers['content-type'] = 'application/json;charset=UTF-8'
    axios({
      method: 'post',
      url: baseUrl + url, // 请求地址
      data: options, // 参数
      responseType: 'blob', // 表明返回服务器返回的数据类型
      headers: {
        Authorization: 'Bearer ' + getToken()
      },
      timeout: 2 * 90 * 1000
    }).then(
      response => {
        resolve(response.data)
        const blob = new Blob([response.data], {
          type: 'application/vnd.ms-excel'
        })
        const fileName = textName
          ? textName
          : Date.parse(new Date().toISOString()) + '.xlsx'
        if ((window.navigator as any).msSaveOrOpenBlob) {
          // console.log(2)
          ;(navigator as any).msSaveBlob(blob, fileName)
        } else {
          // console.log(3)
          const link = document.createElement('a')
          link.href = window.URL.createObjectURL(blob)
          link.download = fileName
          link.click()
          //释放内存
          window.URL.revokeObjectURL(link.href)
        }
      },
      err => {
        reject(err)
      }
    )
  })
}

export function downLoadZip(url, options = {}, textName) {
  return new Promise((resolve, reject) => {
    axios.defaults.headers['content-type'] = 'application/json;charset=UTF-8'
    axios({
      method: 'post',
      url: baseUrl + url, // 请求地址
      data: options, // 参数
      responseType: 'blob', // 表明返回服务器返回的数据类型
      headers: {
        Authorization: 'Bearer ' + getToken()
      }
    }).then(
      response => {
        resolve(response.data)
        const blob = new Blob([response.data], {
          type: 'application/zip'
        })
        console.log(blob)
        const fileName = textName
          ? textName
          : Date.parse(new Date().toISOString()) + '.zip'
        if ((window.navigator as any).msSaveOrOpenBlob) {
          // console.log(2)
          ;(navigator as any).msSaveBlob(blob, fileName)
        } else {
          // console.log(3)
          const link = document.createElement('a')
          link.href = window.URL.createObjectURL(blob)
          link.download = fileName
          link.click()
          //释放内存
          window.URL.revokeObjectURL(link.href)
        }
      },
      err => {
        reject(err)
      }
    )
  })
}
